package cn.fantasy.test.aqs.semaphore;

import java.util.concurrent.Semaphore;

/**
 * @author 使用Semaphore实现限流
 * @description TODO
 * @date 2021/6/21 16:46
 * @Version V1.0
 */
public class SemaphoreDemo {
    public static void main(String[] args) {
        //允许一个线程同时执行
        // Semaphore s = new Semaphore(1);
        // 允许两个纤程同时执行
        Semaphore s = new Semaphore(1);
        //2 同时允许两个线程运行  true 公平与否 默认非公平
        // Semaphore s = new Semaphore(2, true);

        new Thread(() -> {
            try {
                s.acquire();

                System.out.println("T1 running...");
                Thread.sleep(200);
                System.out.println("T1 running...");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                s.release();
            }
        }).start();

        new Thread(() -> {
            try {
                s.acquire();

                System.out.println("T2 running...");
                Thread.sleep(200);
                System.out.println("T2 running...");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                s.release();
            }
        }).start();
    }
}
